package com.example.shw

import android.content.Context
import android.graphics.*
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.support.v7.app.AppCompatActivity
import android.util.DisplayMetrics
import android.util.Log
import android.view.View
import android.view.Window
import android.view.WindowManager
import java.lang.ref.WeakReference
import java.util.*
import kotlin.random.Random

class SmallBallActivity : AppCompatActivity(){
    //屏幕宽度
    private var tableWidth = 0f
    //屏幕高度
    private var tableHeight = 0f
    //球拍的垂直位置
    private var racketY = 0f
    //下面定义球的高度和宽度
    private var racketHeight : Float = 0f
    private var racketWidth : Float = 0f
    //小球的大小
    private var ballSize : Float = 0f
    //小球纵向的运行速度
    private var ySpeed = 11
    private var rand = Random(1)
    //返回一个-0.5~0.5的比率，用于控制小球的运行方向
    private val xyRate = rand.nextDouble() - 0.5
    //小球横向的运行速度
    private var xSpeed = (ySpeed.toDouble() * xyRate * 2.0).toInt()
    //ballx和bally代表小球的坐标
    private var ballx = rand.nextInt(200) + 20f
    private var bally = rand.nextInt(10) + 40f
    //racketX代表球拍的水平位置
    private var racketX = rand.nextInt(200).toFloat()
    //游戏是否结束的旗标
    private var isLose = false
    private lateinit var gameView : GameView

    class MyHandler(private var gameView: WeakReference<SmallBallActivity>) : Handler(){
        override fun handleMessage(msg: Message) {
            when(msg.what){
                0x123 -> gameView.get()?.gameView?.invalidate()
            }
        }
    }
    private val handler = MyHandler(WeakReference(this))

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //去掉窗口标题
        requestWindowFeature(Window.FEATURE_NO_TITLE)
        racketHeight = 30f
        racketWidth = 300f
        ballSize = 10f
        //全屏显示
        window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN)
        gameView = GameView(this)
        setContentView(gameView)
        //获取窗口管理器
        val windowManager = windowManager
        val display = windowManager.defaultDisplay
        val metrics = DisplayMetrics()
        display.getMetrics(metrics)
        //获取屏幕宽和高
        tableWidth = metrics.widthPixels.toFloat()
        tableHeight = metrics.heightPixels.toFloat()
        racketY = tableHeight - 80f
        gameView.setOnTouchListener { _, event ->
            if (event.x <= tableWidth / 10)
            {
                if (racketX > 0) racketX -= 10
            }
            if (event.x >= tableWidth * 9 / 10){
                if (racketX < tableWidth - racketWidth) racketX += 10
            }
            true
        }
        val timer = Timer()
        timer.schedule(object : TimerTask(){
            override fun run() {
                //如果小球碰到左边边框
                if (ballx < ballSize || ballx >= tableWidth - ballSize)
                {
                    xSpeed = -xSpeed
                }
                //如果小球高度超出了球拍位置，且横向不在球拍范围之内，游戏结束
                if (bally >= racketY - ballSize && (ballx < racketX || ballx > racketX + racketWidth))
                {
                    timer.cancel()
                    isLose = true
                }else if (bally < ballSize || (bally >= 2500f - ballSize && ballx > racketX && ballx <= racketX + racketWidth))
                {
                    ySpeed = -ySpeed
                }
                bally += ySpeed
                ballx += xSpeed
                //发送消息，通知系统重绘组件
                handler.sendEmptyMessage(0x123)
            }
        }, 0, 16)
    }

    internal inner class GameView(context: Context) : View(context){
        private var paint = Paint()
        private var mShader = RadialGradient(- ballSize / 2, - ballSize / 2, ballSize,
            Color.WHITE, Color.RED, Shader.TileMode.CLAMP)
        init {
            isFocusable = true
            paint.style = Paint.Style.FILL
            paint.isAntiAlias = true
        }

        override fun onDraw(canvas: Canvas) {
            if (isLose) {
                paint.color = Color.RED
                paint.textSize = 40f
                canvas.drawText("游戏已结束", tableWidth / 2 - 100, 200f, paint)
            }else {
                canvas.save()
                canvas.translate(ballx,bally)
                //设置渐变，并绘制小球
                paint.shader = mShader
                canvas.drawCircle(0f, 0f, ballSize, paint)

                canvas.restore()//恢复原来的坐标系
                paint.shader = null
                //设置颜色，并绘制球拍
                paint.color = Color.BLACK
                Log.d("12345","racketX" + racketX + ";racketY" + racketY)
                canvas.drawRect(racketX, 2500f, racketX + racketWidth,
                    2500f + racketHeight, paint)
            }
        }
    }
}